package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.product.controller.Student;
import com.atguigu.gmall.product.service.TestService;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    //读写锁的读方法
    @Override
    public String readLock() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("readWriteLock");
        readWriteLock.readLock().lock(10L,TimeUnit.SECONDS);
        String msg = redisTemplate.opsForValue().get("msg");

        return msg;
    }

    //读写锁的写方法
    @Override
    public String writeLock() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("readWriteLock");
        readWriteLock.writeLock().lock(10L,TimeUnit.SECONDS);
        redisTemplate.opsForValue().set("msg",UUID.randomUUID().toString());

        return "成功写入了信息。。。。";
    }

    //使用redisson解决分布式事务问题
    @Override
    public void testLock() {

        RLock lock = redissonClient.getLock("lock");
        //上锁并且设置过期时间
        //lock.lock(10L,TimeUnit.SECONDS);
        boolean flag = false;
        try {
            flag = lock.tryLock(100L, 10L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (flag) {
            try {
                String value = redisTemplate.opsForValue().get("num");
                if (StringUtils.isBlank(value)) {
                    return;
                }
                int num = Integer.parseInt(value);
                redisTemplate.opsForValue().set("num", String.valueOf(++num));
            } finally {
                lock.unlock();
            }
        }



        //使用常规可重入锁，锁不自动消失
        /*RLock lock = redissonClient.getLock("lock");
        lock.lock();
        try {
            String value = redisTemplate.opsForValue().get("num");
            if (StringUtils.isBlank(value)){
                return;
            }
            int num = Integer.parseInt(value);
            redisTemplate.opsForValue().set("num",String.valueOf(++num));
        } finally {
            lock.unlock();
        }*/

    }



    //分布式锁
    /*@Override
    public void testLock() {
        //Boolean flag = redisTemplate.opsForValue().setIfAbsent("lock", "ok");
        String uuid = UUID.randomUUID().toString();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent("lock", uuid,3L, TimeUnit.SECONDS);
        if (flag){
            String value = redisTemplate.opsForValue().get("num");
            if (StringUtils.isBlank(value)){
                return;
            }
            int num = Integer.parseInt(value);
            redisTemplate.opsForValue().set("num",String.valueOf(++num));
            //防止删除别的线程的redis锁
            *//*if (uuid.equals(redisTemplate.opsForValue().get("lock"))){
                redisTemplate.delete("lock");
            }*//*
            //使用LUA脚本，保证删除的原子性
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            DefaultRedisScript<Long> redisScript = new DefaultRedisScript();
            redisScript.setScriptText(script);
            redisScript.setResultType(Long.class);
            redisTemplate.execute(redisScript, Arrays.asList("lock"),uuid);
        }else{
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            testLock();
        }
    }*/


    //本地锁的局限性
    /*@Override
    public synchronized void testLock() {
        String value = redisTemplate.opsForValue().get("num");
        if (StringUtils.isBlank(value)){
            return;
        }
        int num = Integer.parseInt(value);
        redisTemplate.opsForValue().set("num",String.valueOf(++num));
    }*/

   /* @Override
    @GmallCache(prefix = "getObject:")
    public Student testGetObject() {
        Student student = new Student(1,"zhangsan");
        return student;
    }*/
    /*@Override
    @GmallCache(prefix = "getObject:")
    public Object testGetObject() {
        Object o = new Object();
        return null;
    }*/
}
